<template>
  <a-textarea :allow-clear="clearable"
              v-model="newValue"
              :disabled="disabled"
              :readOnly="readonly"
              :maxLength="maxLength"
              :placeholder="placeholder"
              @pressEnter="handlePressEnter"
              :auto-size="{ minRows: minRows, maxRows: maxRows }"
              @change="handleChange"
              @blur="handleBlur" />
</template>

<script>
import PropTypes from '@zh/common-utils/prop-types'

export default {
  name: 'ZTextarea',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: PropTypes.string.def(undefined),
    maxLength: PropTypes.number.def(255),
    placeholder: PropTypes.string.def(undefined),
    clearable: PropTypes.bool.def(false),
    disabled: PropTypes.bool.def(false),
    readonly: PropTypes.bool.def(false),
    minRows: PropTypes.number.def(3),
    maxRows: PropTypes.number.def(5)
  },
  watch: {
    minRows () { },
    maxRows () { },
    value: {
      immediate: true,
      deep: true,
      handler (value) {
        this.newValue = value
      }
    }
  },
  data () {
    return {
      newValue: this.value || ''
    }
  },
  methods: {
    handlePressEnter (e) {
      this.emit('pressEnter', e)
    },
    handleChange (e) {
      e.target.value = e.target.value.replace(/[\^\\\\/:\\*\\?"\\|<>]+/g, '')
      this.emit('change', this.newValue)
    },
    handleBlur (e) {
      if (this.newValue.trim().length == 0) {
        this.newValue = ''
        this.handleChange(e)
      }
    },
    emit (eventName, e) {
      this.$emit(eventName, this.newValue)
    }
  }
}
</script>